//
//  MessageViewController.m
//  XMPPMessage
//
//  Created by 刘永杰 on 15/11/21.
//  Copyright © 2015年 刘永杰. All rights reserved.
//

#import "MessageViewController.h"

@interface MessageViewController ()<UITableViewDelegate, UITableViewDataSource, XMPPRosterDelegate, XMPPStreamDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *dataArray;


@end

@implementation MessageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray = [NSMutableArray array];
    
    [[XMPPManager defaultManager].XMPPStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
    
    //coreData在查询数据的时候，多多少少有延迟，所以一定要保证在查完数据之后，让tableView刷新一次
    [self.dataArray setArray:[self findData]];
    
    [self.tableView reloadData];
    
    // Do any additional setup after loading the view.
}

- (NSArray *)findData
{
    
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:[XMPPManager defaultManager].content];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
    
    //barJidStr 代表和我聊天的人的Jid
    //streamBareJidStr 我本人
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"bareJidStr = %@ AND streamBareJidStr = %@", self.toJID.bare, [XMPPManager defaultManager].XMPPStream.myJID.bare];
    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timestamp"
                                                                   ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [[XMPPManager defaultManager].content executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        
        return [NSArray array];
    } else {
        
        NSLog(@"limian :%@", fetchedObjects);
        return fetchedObjects;
    }
}

- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message
{
    [self.dataArray removeAllObjects];
    [self.dataArray setArray:[self findData]];
    [self.tableView reloadData];
    
    NSLog(@"%@", self.dataArray);
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.dataArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

- (void)xmppStream:(XMPPStream *)sender didSendMessage:(XMPPMessage *)message
{
    [self.dataArray removeAllObjects];
    [self.dataArray setArray:[self findData]];
    [self.tableView reloadData];
    
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForItem:self.dataArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    
}

- (IBAction)sendAction:(id)sender {
    
    XMPPMessage *message = [XMPPMessage messageWithType:@"chat" to:self.toJID];
    
    [message addBody:@"你好，早安"];
    
    //发送一条聊天信息
    [[XMPPManager defaultManager].XMPPStream sendElement:message];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Messagecell" forIndexPath:indexPath];
    
    XMPPMessageArchiving_Message_CoreDataObject *object = self.dataArray[indexPath.row];
    
    if (object.isOutgoing) {
        
        cell.detailTextLabel.text = object.body;
        cell.textLabel.text = @"";
    } else {
        cell.textLabel.text = object.body;
        cell.detailTextLabel.text = @"";
    }
    
    return cell;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
